<template>
  <div class="module-layout">
    <je-panel v-bind="options">
      <template #top>
        <source-head />
      </template>
      <template #default>
        <EditorCode
          v-model:value="editorValue"
          v-model:language="language"
          height="100%"
          width="100%"
          @save="onSave"
          @init="onInit"
          @change="onChange"
        />
      </template>
    </je-panel>
  </div>
</template>

<script>
  import { defineComponent, reactive, ref, toRefs, onMounted, inject, toRaw, watch } from 'vue';
  import SourceHead from '@/views/data-source/common/source-head.vue';
  import { EditorCode } from '@jecloud/ui';
  import { useJE } from '@common/helper/je';
  import { execScript, isPromise, isNotEmpty } from '@jecloud/utils';
  import VueEvent from '@/helper/event';
  import { SOURCE_DATA_LABEL, SOURCE_START_RECOVER } from '@/helper/constant';
  import { useSourceStore } from '@/store/source-store';
  import { showModal } from '@/views/data-source/common/execModal.jsx';
  export default defineComponent({
    name: 'SourceJs',
    components: {
      SourceHead,
      EditorCode,
    },
    setup() {
      const sourceStore = useSourceStore(); //数据源全局状态
      const execScriptResult = () => {
        //执行js语句返回结果
        let flag = true;
        if (isNotEmpty(state.editorValue)) {
          flag = execScript(state.editorValue, {
            EventOptions: { isTrusted: true, type: 'dataSource' },
            JE: useJE(),
          });
          if (isPromise(flag)) {
            return flag;
          } else {
            return flag !== false ? Promise.resolve(flag) : Promise.reject();
          }
        }
      };
      const curSourceCode = sourceStore.getSourceCode();
      const curSourceData = sourceStore.getSourceDataByCode(curSourceCode);
      const state = reactive({
        options: {
          top: { size: 40, split: false },
        },
        curTabSourceCode: curSourceCode,
        sourceData: toRaw(inject(SOURCE_DATA_LABEL)), //获取当前数据
        language: 'javascript', //编辑器语言
        //编辑语言
        editorValue: '',
        //默认提示
        defaultEditor: `/**
 * 必须按照如下格式返回数据，否则数据出错，params(过滤条件)可以省略
 * return {
 *    fields:["字段名1","字段名2"],
 *    data:[{字段名1:"A",字段名2:"1"},{字段名1:"B",字段名2:"2"}],
 *    params:[{name:"字段名",label:"字段描述",type:"字段类型"}]
 * };
 */`,
      });
      const methods = {
        onInit($editor) {
          // console.log('初始化：', $editor, editor.value.getEditor());
        },
        onSave(value) {
          //保存 Ctrl + S
          // console.log('保存成功：', value);
        },
        onChange(value, evt) {
          //数据变动
          // console.log('数据变动：', value, evt);
        },

        handleExecData() {
          //开始执行操作
          execScriptResult().then((res) => {
            showModal({ execData: res });
          });
        },
        setSourceConfig(jsConfig) {
          const curSourceCode = sourceStore.getSourceCode();
          const curSourceData = sourceStore.getSourceDataByCode(curSourceCode);
          curSourceData.DATASOURCE_CONFIG = jsConfig;
        },
        //复原操作
        startRecoverData(sourceCode) {
          if (sourceCode == state.curTabSourceCode) {
            const curSourceData = sourceStore.getSourceDataByCode(sourceCode);
            state.editorValue = curSourceData.DATASOURCE_CONFIG || state.defaultEditor;
          }
        },
      };
      watch(
        () => state.editorValue,
        (val) => {
          methods.setSourceConfig(val);
        },
      );
      onMounted(() => {
        state.editorValue = curSourceData.DATASOURCE_CONFIG || state.defaultEditor;
        VueEvent.on(SOURCE_START_RECOVER, methods.startRecoverData);
      });
      return {
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style scoped lang="less">
  .module-layout {
    width: 100%;
    height: 100%;
  }
</style>
